package com.dcivision.framework.web;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.ProtectedObject;
import com.dcivision.framework.bean.ProtectedResource;
import com.dcivision.framework.dao.ProtectedObjectDAObject;

public class AbstractBaseObjectProtectedFilterHelper extends DefaultProtectedFilterHelper {
  
  private static final Log log = LogFactory.getLog(AbstractBaseObjectProtectedFilterHelper.class);
  
  private Map protectedID = null;
  
  public AbstractBaseObjectProtectedFilterHelper ( SessionContainer sessionContainer, Connection dbConn){
    super ( sessionContainer, dbConn );
  }

  public void setProtectedResourceList(List protectedResourceList){
    super.setProtectedResourceList(protectedResourceList);
    try {

      if (!Utility.isEmpty(this.getProtectedResourceList())) {
        for(int i = 0; i < this.getProtectedResourceList().size(); i++) {
          ProtectedResource protectedResource = (ProtectedResource)this.getProtectedResourceList().get(i);
          ProtectedObjectDAObject protectedObjectDAO = new ProtectedObjectDAObject(this.sessionContainer, this.dbConn);
          List objectList = protectedObjectDAO.getListBySourceID(protectedResource.getID());
          if (!Utility.isEmpty(objectList)) {
            protectedID = new HashMap();
            for ( int j = 0 ; j < objectList.size() ; j++ ){
            ProtectedObject protectedObject = (ProtectedObject)objectList.get(j);
            protectedID.put(protectedObject.getObjectValue(), protectedObject);
            }
          }
        }
      }
    } catch (Exception ex) {
      log.error(ex, ex);
    } 
  }

  public boolean isProtected(HttpServletRequest request)throws Exception{
    if(super.isProtected(request)){
      // check if the requesting URI is protected
      if (protectedID!=null) {
        if (protectedID.containsKey(request.getParameter("ID"))) {
          request.getSession().setAttribute("Current_Protected_Object", new Integer(request.getParameter("ID")));
          return true;
        }
      }
    }
    return false;
  }

}
